package com.learn.excel.core.util;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import static cn.hutool.core.util.CharsetUtil.ISO_8859_1;
import static cn.hutool.core.util.CharsetUtil.UTF_8;
import static cn.hutool.http.ContentType.MULTIPART;
import static cn.hutool.http.Header.CONTENT_DISPOSITION;
import static cn.hutool.http.Header.USER_AGENT;

@Slf4j
public class FileUtil {

    /***
     * 生成文件输出流
     * @param fileName
     * @param fileInputStream
     * @param request
     * @param response
     * @return
     */
    public static void writeFile(String fileName, InputStream fileInputStream, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //  文件存在才下载
        OutputStream out = null;
        FileInputStream in = null;
        try {
            String agent = request.getHeader(USER_AGENT.toString());
            if (agent.contains("FireFox")) {
                fileName = new String(fileName.getBytes(UTF_8), ISO_8859_1);
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            // 设置下载文件的mineType，告诉浏览器下载文件类型
            String mineType = request.getServletContext().getMimeType(fileName);
            response.setContentType(mineType);
            // 设置一个响应头，无论是否被浏览器解析，都下载
            response.setHeader(CONTENT_DISPOSITION.toString(), "attachment; filename=" + fileName);
            // 将要下载的文件内容通过输出流写到浏览器
            out = response.getOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = fileInputStream.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }

        } catch (Exception ex) {
            log.error(ex.getMessage());
        } finally {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        }
    }

    /**
     * 生成文件输出流
     *
     * @param response
     * @param fileInputStream
     * @return
     */
    public static void writeFile(HttpServletResponse response, InputStream fileInputStream) {
        ServletOutputStream outputStream = null;
        try {
            response.setContentType(MULTIPART.toString());
            outputStream = response.getOutputStream();
            //读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成文件输出流
     *
     * @param fileName
     * @param fileInputStream
     * @param response
     * @return
     */
    public static void writeFile(String fileName, InputStream fileInputStream, HttpServletResponse response) throws IOException {
        final String contentType = ObjectUtil.defaultIfNull(cn.hutool.core.io.FileUtil.getMimeType(fileName), "application/octet-stream");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        cn.hutool.extra.servlet.ServletUtil.write(response, fileInputStream, contentType, fileName);
    }
}
